package com.younio.local.entity.Line2;

import com.younio.local.entity.TI;
import com.younio.local.util.Objects;
import com.younio.local.util.Sequence;
import lombok.*;

import java.util.*;
import java.util.stream.Collectors;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Line {

    private String uuid;

    private int line;

    private String operator;

    private String taskUuid;

    private String stationUuid;

    private int num;

    private List<TI> tiList;

    private List<Integer> indexList;
    private Set<Integer> indexSet;

    private boolean inited;

    private boolean ignoreErr;


    public int getNum() {
        if (num == 0) {
            if (tiList != null) {
                num = tiList.size();
            }
        }
        return num;
    }

    public boolean hasTid() {
        this.tiList = Objects.emptyToNull(this.tiList);
        return this.tiList != null;
    }

    private Map<Integer, String> tidIndexMap;

    public void init() {
        if (hasTid()) {
            this.tidIndexMap = tiList.stream().collect(Collectors.toMap(TI::getIndex, TI::getTid));
            this.indexList = tiList.stream().map(TI::getIndex).distinct().collect(Collectors.toList());
            Objects.checkArguments(indexList.stream().distinct().count() == indexList.size(), "参数错误,位置重复");
        } else {
            indexList = new LinkedList<>();
            for (int i = 1; i < num + 1; i++) {
                indexList.add(i);
            }
        }
        this.indexSet = new HashSet<>(indexList);
        this.indexList = Objects.emptyToNull(indexList);
        inited = true;
    }

    public boolean isInited() {
        if (!inited) {
            init();
        }
        return inited;
    }

    /**
     * @param index 天马数据库中的位置
     * @return String tid字符串
     * @desc 获取指定位置的tid, 如果没有tid返回seq+"#"
     * @author lan [1728209643@qq.com]
     * @create 2019/1/3 8:58
     */
    public String getTid(int index) {
        return hasTid() ? tidIndexMap.get(index) : Sequence.get() + "#";
    }

}
